<template>
    <n-form
        ref="formRef"
        label-placement="top"
        :label-width="80"
        :model="form"
        :rules="rules"
        class="mt-24px"
    >
        <!--编辑页面-->
        <n-form-item label="名称" path="name">
            <n-input
                v-model:value="form.name"
                maxlength="20"
                :type="props.id ? 'text' : 'textarea'"
                :placeholder="
                    props.id
                        ? '请输入名称'
                        : '请输入名称 如有多个用空格隔开 单个长度需<=100'
                "
            />
        </n-form-item>
        <n-form-item label="编码(SN)">
            <n-input
                v-model:value="form.sn"
                :type="props.id ? 'text' : 'textarea'"
                :placeholder="
                    props.id
                        ? '请输入编码'
                        : '请输入编码 如有多个用空格隔开 编码数量需要和名称数量保持一致'
                "
            />
        </n-form-item>
    </n-form>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import type { FormInst, FormRules } from 'naive-ui'
import { Rules } from '@/utils'
import { JBoltApi } from '@/utils/request'
import { useResetableData } from '@/hooks/common/use-resetable-data'
import { ResData } from '@/typings/request'

const props = withDefaults(
    defineProps<{
        id?: string
        pid?: string
    }>(),
    {
        id: '',
        pid: '0'
    }
)

/** 表单相关 start */
const formRef = ref<FormInst | null>()
interface RoleType {
    id: string
    pid: string
    name: string
    sn: string
}
const form = useResetableData<RoleType>({
    id: '',
    name: '',
    sn: '',
    pid: ''
})
const rules: FormRules = {
    name: new Rules().required('请输入名称').value
}

/**
 * 提交表单
 */
async function submit() {
    await formRef.value?.validate()

    let url = props.id ? '/api/admin/role/update' : '/api/admin/role/save'
    let res = await JBoltApi.tryPost(url, form)
    await window.$success('保存成功')
    return res.data
}

function loadEditData() {
    JBoltApi.get<ResData>(`/api/admin/role/${props.id}`).then(({ error, result }) => {
        if (error) return
        form._reset(result.data)
    })
}

onMounted(() => {
    if (props.id) {
        loadEditData()
    } else {
        form.pid = props.pid
    }
})

defineExpose({
    submit
})

/** 表单相关 end */
</script>
<style scoped></style>
